const path = require('path');
const { loaderByName, addBeforeLoader } = require('@craco/craco');

const packageRootPath = path.resolve(__dirname, '../commons');

function addLoadersForWorkersAndPackages(webpackConfig) {
  addBeforeLoader(webpackConfig, loaderByName('babel-loader'), {
    test: /\.worker\.(ts|js)$/,
    use: [
      {
        loader: 'worker-loader',
        options: {
          filename:
            process.env.NODE_ENV === 'production'
              ? `static/js/[name].[chunkhash:8].chunk.js`
              : 'static/js/[name].js',
        },
      },
      {
        loader: 'ts-loader',
        options: {
          transpileOnly: true,
        },
      },
    ],
  });

  addBeforeLoader(webpackConfig, loaderByName('babel-loader'), {
    test: /\.(js|jsx|ts|tsx)$/,
    include: [packageRootPath],
    loader: 'babel-loader',
    options: {
      presets: [
        '@babel/preset-env',
        '@babel/preset-typescript',
        '@babel/preset-react',
      ],
    },
  });
}

module.exports = { addLoadersForWorkersAndPackages };
